import os
import sys
import shutil
from datetime import datetime

def connect_server(server_path):
    # 检查路径是否存在
    if os.path.exists(server_path):
        print(server_path,"连接成功！",datetime.now())

    else:
        print("连接不上，请检查")
        sys.exit(1)

def download_file(server_path,local_path):
    # 遍历下载最新的word文件
    try:
        # 获取源目录中所有word文件的路径和修改时间
        #用列表解析代替下面的循环
        remotedocfiles = [
            (os.path.join(server_path, filename), os.path.getmtime(os.path.join(server_path, filename)))
            for filename in os.listdir(server_path)
            if (filename.endswith('.doc') or filename.endswith('.docx')) and filename.startswith('重要气象信息')
        ]
        # remotedocfiles = []
        # for filename in os.listdir(server_path):
        #     if filename.endswith('.doc') or filename.endswith('.docx'):
        #         if filename.startswith('重要气象信息'):
        #             remotedocfiles.append((os.path.join(server_path, filename),os.path.getmtime(os.path.join(server_path, filename))))

        # 获得最新的文件到变更时间
        if remotedocfiles == []:
            print('没有合适的文档')
            sys.exit(1)
        else:
            # 根据修改时间对文件进行排序
            remotedoc = sorted(remotedocfiles, key=lambda x: x[1], reverse=True)
            latest_remotefile = remotedoc[0][0]
            latest_remotefile_mtime = remotedoc[0][1]
            #找出本地文件的最新时间
            localdocfiles = [
                (os.path.join(local_path, filename),os.path.getmtime(os.path.join(local_path, filename)))
                for filename in os.listdir(local_path)
                if (filename.endswith('.doc') | filename.endswith('.docx')) and filename.startswith('重要气象信息')
            ]
            localdoc = sorted(localdocfiles,key=lambda x: x[1], reverse=True)
            localfilename = os.path.join(local_path, os.path.basename(latest_remotefile))

            # 如果服务器文件时间比本地新，复制最新的文件到本机目录
            if localdoc:
                latest_localfile_mtime = localdoc[0][1]
                if latest_remotefile_mtime > latest_localfile_mtime:
                    print('现在复制', latest_remotefile, '...')
                    shutil.copy2(latest_remotefile, localfilename)
                    print(os.path.basename(latest_remotefile), '已成功复制')
                else:
                    print('文件没有更新')
                    sys.exit(1)
            else:
                print('现在复制', latest_remotefile, '...')
                shutil.copy2(latest_remotefile, localfilename)
                print(os.path.basename(latest_remotefile), '已成功复制')

    except Exception as e:
        print("Error:", e)
        sys.exit(1)


# 定义服务器共享文件夹路径
server_path1 = "\\\\192.168.110.109\\hxq"
local_path1 = "e:\\hxq"

connect_server(server_path1)
download_file(server_path1, local_path1)